package me.gm.stcont.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.gm.stcont.Error;
import me.gm.stcont.Utils;
import me.gm.stcont.model.User;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController extends BaseController {

	private final List<Integer> NOT_DELETE_IDS;

	public UserController() {
		NOT_DELETE_IDS = Arrays.asList(1, 2, 3);
	}

	@RequestMapping(value = "/users")
	public String list(@RequestParam(required = false) Boolean paging,
			@RequestParam(required = false) Integer start,
			@RequestParam(required = false) Integer offset, Model model) {
		getLogger().info("started list");

		if (getLogger().isEnabledFor(Level.DEBUG)) {
			getLogger().debug("paging: " + paging);
			getLogger().debug("start: " + start);
			getLogger().debug("offset: " + offset);
		}

		Sort sort;

		sort = new Sort("userName", "id");

		model.addAttribute("action", "list");
		model.addAttribute("success", true);

		if (paging != null && paging.booleanValue()) {
			if (start == null) {
				start = 0;
			}

			if (offset == null) {
				offset = getPropertiesWrapper().getPaginationSize();
			}

			Page<User> users;

			users = getUserRepository().findAll(
					getPageable(start, offset, sort));

			model.addAttribute("page", users);
		} else {
			List<User> users;

			users = getUserRepository().findAll(sort);

			model.addAttribute("entities", users);
		}

		getLogger().info("finished list");

		return "user";
	}

	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
	public String remove(@PathVariable("id") Integer id, Model model) {
		getLogger().info("started remove");

		if (getLogger().isEnabledFor(Level.DEBUG)) {
			getLogger().debug("id: " + id);
		}

		List<Error> errors;

		errors = new ArrayList<Error>();

		boolean success;

		success = false;

		if (NOT_DELETE_IDS.contains(id)) {
			Utils.addError(errors, "7");
		} else {
			if (getUserRepository().findOne(id) == null) {
				Utils.addError(errors, "1");
			}
		}

		if (errors.isEmpty()) {
			getUserRepository().delete(id);

			success = true;
		}

		model.addAttribute("action", "remove");
		model.addAttribute("success", success);
		model.addAttribute("errors", errors);

		getLogger().info("finished remove");

		return "user";
	}

	@RequestMapping(value = "/user/{id}")
	public String get(@PathVariable("id") Integer id, Model model) {
		getLogger().info("started get");

		if (getLogger().isEnabledFor(Level.DEBUG)) {
			getLogger().debug("id: " + id);
		}

		List<Error> errors;

		errors = new ArrayList<>();

		boolean success;

		success = false;

		User user;

		user = getUserRepository().findOne(id);

		if (user == null) {
			Utils.addError(errors, "1");
		}

		if (errors.isEmpty()) {
			success = true;
		}

		model.addAttribute("action", "get");
		model.addAttribute("success", success);
		model.addAttribute("entity", user);
		model.addAttribute("errors", errors);

		getLogger().info("finished get");

		return "user";
	}

	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public String save(User user, Model model) {
		getLogger().info("started save");

		if (getLogger().isEnabledFor(Level.DEBUG)) {
			getLogger().debug("user: " + user);
		}

		List<Error> errors;

		errors = new ArrayList<Error>();

		boolean success;

		success = false;

		if (user == null) {
			Utils.addError(errors, "3");
		} else {
			if (user.getId() == null) {
				Utils.addError(errors, "4", "field=userId");
			}
			if (StringUtils.isBlank(user.getUserName())) {
				Utils.addError(errors, "5", "field=userUserName");
			} else {
				if (user.getUserName().length() > 10) {
					Utils.addError(errors, "6", "field=userUserName",
							"maximum=10");
				}

				User userSaved;

				userSaved = getUserRepository().findByUserName(
						user.getUserName());

				if (userSaved != null
						&& !userSaved.getId().equals(user.getId())) {
					Utils.addError(errors, "8", "field=userUserName");
				}
			}
			if (user.getId() == 0 && StringUtils.isBlank(user.getPassword())) {
				Utils.addError(errors, "5", "field=userPassword");
			}
			if (StringUtils.isNotBlank(user.getPassword())
					&& user.getPassword().length() > 8) {
				Utils.addError(errors, "6", "field=userPassword", "maximum=8");
			}
		}

		if (errors.isEmpty()) {
			if (StringUtils.isNotBlank(user.getPassword())) {
				user.setPassword(Utils.encodePassword(user.getPassword()));
			}

			user = getUserRepository().save(user);

			success = true;
		}

		model.addAttribute("action", "save");
		model.addAttribute("success", success);
		model.addAttribute("entity", user);
		model.addAttribute("errors", errors);

		getLogger().info("finished save");

		return "user";
	}

}
